package com.rtsapp.server.platform.google;

import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;

import com.rtsapp.server.app.AppConfig;
import com.rtsapp.server.logger.Logger;
import com.rtsapp.server.logger.LoggerFactory;
import com.rtsapp.server.platform.IPlatformLoginService;

import java.util.Collections;

/**
 * Created by admin on 17-8-24.
 */
public class GooglePlayPlatformAndroidLoginService implements IPlatformLoginService {

    private static final Logger LOGGER = LoggerFactory.getLogger( GooglePlayPlatformLoginService.class );

    private static final String GOOGLE_APP_ID = AppConfig.getInstance().getGoogleAndroidAppId();

    @Override
    public String validateLoginToken(String token, String uid) {
        if (token == null) {
            return null;
        }
        LOGGER.info("google 登录 sdk_token:" + token);
        try {
            GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(new NetHttpTransport(), new JacksonFactory()).setAudience(Collections.singletonList(GOOGLE_APP_ID)).build();
            GoogleIdToken googleIdToken = verifier.verify(token);
            if (googleIdToken != null) {
                GoogleIdToken.Payload payload= googleIdToken.getPayload();
                return payload.getSubject();
            }
        } catch (Exception e) {
            LOGGER.error("google 登录错误 返回:", e);
            return null;
        }
        return null;
    }
}
